import axios from 'axios';
import { getStorage, isFunction } from '@wowon/utils';
import { STORAGE_NAMES } from '@/common/constant';
import reqTypes from '@/common/shared/req-types';
// import { refreshToken as refreshTokenApi } from '@/services/login';
// import logout from './logout';

import serverPath from './request-interceptor/server-path';
// import abort from './request-interceptor/abort';
// import withHeader from './request-interceptor/with-header';
import format from './request-interceptor/format';
// import refreshToken from './request-interceptor/refresh-token';

const request = axios.create({
  timeout: 5000,
  getHeaders() {
    return {
      accept: 'application/json;charset=UTF-8',
      authorization: getStorage(STORAGE_NAMES.token),
    };
  },
});

// interceptors request 后面的最先执行
// request.interceptors.request.use(abort.request);
// request.interceptors.request.use(withHeader);
request.interceptors.request.use((config) => {
  const result = format.request(config.url, config);
  return Object.assign({}, config, result.options);
});
request.interceptors.request.use(async function (config) {
  try {
    if (isFunction(config.fakeApi)) {
      config.fakeData = await config.fakeApi(config.params || config.data);
    }
  } catch (error) {
    console.error(error);
  }
  return config;
});
request.interceptors.request.use((config) => {
  const result = serverPath(config.url, config);
  return Object.assign({}, config, result.options, { url: result.url });
});

// interceptors response 前面的最先执行
// request.interceptors.response.use(abort.response);
request.interceptors.response.use(function (response) {
  if (!!response.config.fakeData) {
    response.data = response.config.fakeData;
    delete response.config.fakeData;
  }
  return response;
});
request.interceptors.response.use(
  format.response({
    reqTypes,
    onMessage: (msg, pass) => {
      console.log(msg, pass);
      // message[pass ? 'success' : 'error'](msg);
    },
  })[0],
);
// request.interceptors.response.use( refreshToken.response({
//   refresh: refreshTokenApi,
//   onFail: logout,
// }));
request.interceptors.response.use(function (response) {
  // 最后一个默认返回响应数据
  return response.data;
});

export { request };

export default request;
